package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单业务实现
 *
 * @Author itcast
 * @Create 2023/4/29
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public Orders submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 数据的合法性检查(检查地址id、购物车)
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        if(addressBookId == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
//
//        //检查用户的收获地址是否超出配送范围
//        checkOutOfRange();

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build());
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        AddressBook addressBook = addressBookMapper.getById(addressBookId);


//        //5.3
//        Map<String,String> map = new HashMap<>();
//        map.put("address",addressBook.getDetail());
//        map.put("ak","QhUqB40SwHIFYbxoeR3UfSAMu546DVcH");
//        map.put("output","json");
//
//
//
//        String reponse = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//
//        JSONObject jsonObject = JSON.parseObject(reponse);
//
//        jsonObject = (JSONObject) jsonObject.get("result");
//
//        jsonObject = (JSONObject) jsonObject.get("location");
//
//        BigDecimal lat = jsonObject.getBigDecimal("lat");
//        BigDecimal lng = jsonObject.getBigDecimal("lng");
//        String destination = lat + "," + lng;

//        //
//        Map<String,String> mapO = new HashMap<>();
//        mapO.put("address","北京市海淀区上地十街10号");
//        mapO.put("ak","QhUqB40SwHIFYbxoeR3UfSAMu546DVcH");
//        mapO.put("output","json");
//        String reponse0 = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", mapO);
//
//        JSONObject jsonObject0 = JSON.parseObject(reponse0);
//
//        jsonObject0 = (JSONObject) jsonObject0.get("result");
//
//        jsonObject0 = (JSONObject) jsonObject0.get("location");
//
//        BigDecimal lat0 = jsonObject0.getBigDecimal("lat");
//        BigDecimal lng0 = jsonObject0.getBigDecimal("lng");
//        String origin = lat0 + "," + lng0;
//
//
//        //
//        Map<String,String> map2 = new HashMap<>();
//
//
//        map2.put("origin",origin);
//        map2.put("destination",destination);
//        map2.put("ak","QhUqB40SwHIFYbxoeR3UfSAMu546DVcH");
//
//        String reponse2 = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map2);
//        System.out.println(reponse2);
//        JSONObject jsonObject2 = JSON.parseObject(reponse2);
//        jsonObject2 = (JSONObject) jsonObject2.get("result");
//        JSONArray routes = jsonObject2.getJSONArray("routes");
//        JSONObject o = (JSONObject) routes.get(0);
//        Integer distance1 = o.getInteger("distance");
//
//
//        if (distance1 >= 5000){
//            throw new OrderBusinessException("超出配送范围，下单失败~");
//        }



        // 向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setUserName(addressBook.getConsignee());
        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList  =new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        // 向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());


        /////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////

        return orders;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        orderMapper.update(orders);
    }


    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();//new出来的对象都是空值需要赋值
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());//向DTO里赋值一个userId
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) { //Total页面数量>0
            for (Orders orders : page) {
                Long orderId = orders.getId();  // 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);//把在orderDetails查询出的数据赋值给orderVO

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

//    /**
//     * 历史方法的查询
//     * @param ordersPageQueryDTO
//     * @return
//     */
//    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
//        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
//        Page<OrderVO> pages = orderMapper.pageQuery(ordersPageQueryDTO);
//        //创建一个用于返回订单明细的容器
//        List<OrderVO> list = new ArrayList<>();
//
//        if (pages != null && pages.getTotal() > 0) {
//            for (Orders orders : pages) {
//                //每一条订单的id
//                Long id = orders.getId();
//                //根据订单id查询到订单明细的信息
//                List<OrderDetail> orderDetails =orderDetailMapper.getByOrderId(id);
//                //new一个VO做为返回容器
//                OrderVO orderVO = new OrderVO();
//
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//
//                list.add(orderVO);
//            }
//        }
//        return new PageResult(pages.getTotal(),list);
//    }




    /**
     * 订单详细查询
     * @param id
     * @return
     */
    public OrderVO getById(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }



    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /**
     * 再来一单
     * @param id
     */
    public void repeti(Long id) {
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);//搜索菜品存入集合
        for (OrderDetail orderDetail : list) {//orderDetail是list中的每一个元素
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }


    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }






    /**
     * 各个状态的订单数量统计
     * @return
     */
    public OrderStatisticsVO searchStatis() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待派送数量3
        orderStatisticsVO.setConfirmed(orderMapper.searchStatis3());
        //待接单数量2
        orderStatisticsVO.setDeliveryInProgress(orderMapper.searchStatis4());
        //派送中数量4
        orderStatisticsVO.setToBeConfirmed((orderMapper.searchStatis2()));
        return orderStatisticsVO;
    }


    /**
     * 查询订单详情
     * @return
     */
    public OrderVO adminGetById(Long id) {
        OrderVO orderVO = orderMapper.adminGetById(id);

        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(list);
       return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void updateConfirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.updateConfirm(ordersConfirmDTO.getId());
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void updateReject(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.updateReject(ordersRejectionDTO.getRejectionReason(),ordersRejectionDTO.getId());

        ////
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if (orders.getStatus() >= 2){   //2待接单

            String orderNumber = orders.getNumber();    //获取订单编号

            BigDecimal total = new BigDecimal(0.01);


            //发起退款申请
            try {
                weChatPayUtil.refund(orderNumber, orderNumber, total, total);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    public void updateCancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.updateCancel(ordersCancelDTO.getId(),ordersCancelDTO.getCancelReason());

        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //        String orderNumber = UUID.randomUUID().toString().replace("-","");//商户订单号，申请退款时还需要使用
        if (orders.getStatus() >= 2){
            String orderNumber = orders.getNumber();
//            System.out.println("商户订单号:" + orderNumber);
            BigDecimal total = new BigDecimal(0.01);
//            String description = "苍穹外卖订单";
            //本地支付下单，生成支付链接，前端可以基于支付链接生成二维码，由微信用户扫描支付
//        String code_url = null;
//        try {
//            code_url = weChatPayUtil.nativePay(orderNumber, total, description);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println(code_url);

//        String orderNumber = "843e9df1624c40a5b472587e89f0b3dc"; //商户订单号，退款时需要填入支付时使用的商户订单号
//        BigDecimal total = new BigDecimal(0.01);//退款金额，需要和支付时的支付金额一致，否则无法退款
//            String res = null;//发起退款申请
            try {
                weChatPayUtil.refund(orderNumber, orderNumber, total, total);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            System.out.println(res);
        }
    }

    /**
     * 订单派送
     * @param id
     */
    public void updateDelivery(Integer id) {
        orderMapper.updateDelivery(id);
    }

    /**
     * 完成订单
     * @param id
     */
    public void updateComplete(Integer id) {
        orderMapper.updateComplete(id);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject jsonArray = (JSONObject) result.get("routes");
        JSONArray jsonArray1 =jsonArray.getJSONArray("location");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 客户催单
     * @param id
     */
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号：" + orders.getNumber());

        String json = JSON.toJSONString(map);
        //向客户端推送消息
        webSocketServer.sendToAllClient(json);
    }
}
